<template>
  <div class="login-cnotain">
    <el-card class="box-card">
      <h3>嗨购商城后台管理系统</h3>
      <el-divider border-style="dashed" />
      <el-form
        ref="formRef"
        :model="ruleForm"
        :rules="rules"
        label-width="80px"
        class="demo-ruleForm"
        label-position="left"
        size="large"
      >
        <el-form-item label="用户名:" prop="adminname">
          <el-input v-model="ruleForm.adminname" />
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input v-model="ruleForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label-width="0">
          <el-button type="primary" @click="onLogin" style="width: 100%">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { login } from '@/api/user'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
const router = useRouter()
const store = useUserStore()
const ruleForm = reactive({
  adminname: 'admin',
  password: '123456'
})
const rules = reactive({
  adminname: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 5, message: '用户名必须至少5位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, message: '密码必须至少6位', trigger: 'blur' }
  ]
})
const formRef = ref<FormInstance>()
const onLogin = () => {
  formRef.value.validate(async valid => {
    if (!valid) return
    //发送请求
    const res = await login({ adminname: ruleForm.adminname, password: ruleForm.password })
    // console.log(res.data)
    if (res.data.code === 200) {
      ElMessage({
        showClose: true,
        message: '登录成功'
      })
      //把用户信息存储到仓库
      store.setUserInfo(res.data.data)
      // 登录成功跳转
      router.push('/')
    } else {
      ElMessage.error('用户名或密码错误!')
    }
  })
}
</script>

<style lang="less" scoped>
.login-cnotain {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  .box-card {
    width: 440px;
    height: 320px;
  }
  h3 {
    text-align: center;
  }
}
</style>
